package Search;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import utils.ElasticSearchClient;
import java.util.Map;

/**
 * @author：PZ
 * @Date: 2020/12/11 15 45
 */
public class Search4 {
    ObjectMapper mapper = new ObjectMapper();
    RestHighLevelClient client = ElasticSearchClient.getClient();
    String index = "sms-logs-index";
    String type = "sms-logs-type";
    
    /**
     * scroll深分页查询
     *
     * @throws Exception
     */
    @Test
    public void scrollSearch() throws Exception {
        SearchRequest request = new SearchRequest(index);
        request.types(type);
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //构建scroll条件
        request.scroll(TimeValue.timeValueMinutes(1));
        builder.size(3);
        builder.sort("fee", SortOrder.DESC);
        builder.query(QueryBuilders.matchAllQuery());
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        String scrollId = response.getScrollId();
        SearchHit[] hits = response.getHits().getHits();
        System.out.println("第一页");
        for (SearchHit hit : hits) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            System.out.println(sourceAsMap);
        }
        //循环查询下一页
        while (true) {
            SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
            //查询下一页时，续上scrollId在内存的存在时间
            scrollRequest.scroll(TimeValue.timeValueMinutes(1));
            SearchResponse searchResponse = client.scroll(scrollRequest, RequestOptions.DEFAULT);
            if (searchResponse.getHits().getHits() != null && searchResponse.getHits().getHits().length > 0) {
                System.out.println("下一页");
                for (SearchHit hit : searchResponse.getHits().getHits()) {
                    Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                    System.out.println(sourceAsMap);
                }
            } else {
                System.out.println("结束");
                break;
            }
        }
        //清除es缓存，根据scrollId，因为保存了一分钟
        ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
        clearScrollRequest.addScrollId(scrollId);
        client.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
    }
}
